package com.example.common.util;

import com.example.common.api.ResultCode;
import com.example.common.exception.BizException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * JwtToken生成的工具类
 */
@Slf4j
@SuppressWarnings("unused")
public class JwtTokenUtil {
    private static final String CLAIM_KEY_CREATED = "created";

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 根据负责生成JWT的token
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    private Optional<Claims> getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.info("JWT格式验证失败:{}",token);
        }
        return Optional.ofNullable(claims);
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + expiration * 1000);
    }

    /**
     * 从token中获取登录用户名
     */
    public String getUserNameFromToken(String token) {
        return getClaimsFromToken(token)
                .map(Claims::getSubject)
                .orElse(StringUtils.EMPTY);
    }

    /**
     * 验证token是否还有效
     *
     * @param token       客户端传入的token
     * @param userDetails 从数据库中查询出来的用户信息
     */
    public boolean validateToken(String token, UserDetails userDetails) {
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername()) && isTokenNotExpired(token);
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenNotExpired(String token) {
        return getExpiredDateFromToken(token)
                .map(expiredDate -> expiredDate.after(new Date()))
                .orElse(false);
    }

    /**
     * 从token中获取过期时间
     */
    private Optional<Date> getExpiredDateFromToken(String token) {
        return getClaimsFromToken(token)
                .map(Claims::getExpiration);
    }

    /**
     * 根据用户信息生成token
     */
    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(Claims.SUBJECT, userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED, System.currentTimeMillis()/1000);
        return generateToken(claims);
    }

    /**
     * 判断token是否可以被刷新
     */
    public boolean canRefresh(String token) {
        return isTokenNotExpired(token);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        Claims claims = getClaimsFromToken(token)
                .orElseThrow(()-> new BizException(ResultCode.UNAUTHORIZED));
        claims.put(CLAIM_KEY_CREATED, System.currentTimeMillis()/1000);
        return generateToken(claims);
    }
}
